package com.bieyang.anjia.ui.activity;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import android.app.AlertDialog;
import android.app.Dialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.content.pm.PackageManager.NameNotFoundException;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Environment;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.Window;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.LinearLayout;
import android.widget.ProgressBar;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.bieyang.anjia.R;
import com.bieyang.anjia.module.TNewVerInfo;
import com.bieyang.anjia.utils.Constants;
import com.bieyang.anjia.utils.SharedPrefsUtil;
import com.bieyang.anjia.utils.Show;
import com.bieyang.anjia.utils.Util;

/**
 * 关于，当前版本显示，如果有新版本则提示更新 New Version info
 * 
 * @author wjh
 * */
public class AcAbout extends BaseFlingActivity {
	Button btnBack;
	RelativeLayout rlNewVersion;

	private static final int UPDATA = 1;
	Context con;
	String newVersion;
	boolean isFinish = false;

	private int index = 0;
	private ProgressBar progressBar;

	int fileSize;
	LinearLayout llArrow;

	String url;
	TextView tvVersionInfo, currentVersion;

	public Dialog dialog, progressDialog;
	// public TNewVerInfo verinfo;
	String rVersion, lVersion;

	public Handler Uihandler = new Handler() {
		public void handleMessage(Message msg) {
			switch (msg.what) {
			case UPDATA:
				progressBar.setProgress(index);
				if (index >= 99) {
					progressDialog.dismiss();
				}
				SharedPrefsUtil.putValue(App.mContext, "newVersion", 0);
				break;
			 

			default:
				break;
			}
		};
	};

	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.my_setting_about);
		con = AcAbout.this;
		initView();
		initData();

	}

	private void initView() {
		OnClick onClick = new OnClick();
		btnBack = (Button) findViewById(R.id.btnBack);
		btnBack.setOnClickListener(onClick);

		tvVersionInfo = (TextView) findViewById(R.id.tvVersionInfo);
		currentVersion = (TextView) findViewById(R.id.currentVersion);

		llArrow = (LinearLayout) findViewById(R.id.llArrow);
		rlNewVersion = (RelativeLayout) findViewById(R.id.rlNewVersion);
		rlNewVersion.setOnClickListener(onClick);
	}

	class OnClick implements android.view.View.OnClickListener {
		@Override
		public void onClick(View v) {
			switch (v.getId()) {
			case R.id.btnBack:
				finish();
				break;
			case R.id.rlNewVersion:
				// //获取服务器版本号和当前版本号进行比较，如果是最新版则提示是最新版，如果有新版提示是否下载更新
				if (0 != SharedPrefsUtil.getIntValue(App.mContext,
						"newVersion", 0))
					popUpVersion(2);

				break;
			default:
				break;
			}
		}
	}

	void initData() {
		currentVersion.setText("v" + Util.getVersionName(con));
		// 检测版本更新,只做记录，不做界面处理，界面处理在下一个界面做
//		App.netManager.getVersionInfo(Uihandler); 
		if (0 != SharedPrefsUtil.getIntValue(App.mContext, "newVersion", 0)) {
			llArrow.setVisibility(View.VISIBLE);
			tvVersionInfo.setText(R.string.version_new);
		}

	}

	/**
	 * 下载更新，弹窗升级
	 * 
	 * @param typeUpgrade
	 *            ：2
	 */
	void popUpVersion(final int typeUpgrade) {

		dialog = new Dialog(con);
		LayoutInflater inflater = LayoutInflater.from(con);// 初始化
		View view = inflater.inflate(R.layout.pop_version_upgrade, null);
		TextView tvTitle = (TextView)view.findViewById(R.id.tvTitle);
		tvTitle.setText("v"+App.verinfo.sNewVerNo+"升级内容");
		TextView tvUpContent = (TextView) view.findViewById(R.id.tvUpContent);
		tvUpContent.setText(App.verinfo.sUpMsg);

		// 点确定，开始下载更新
		view.findViewById(R.id.exitBtn0).setOnClickListener(
				new OnClickListener() {
					@Override
					public void onClick(View v) {
						// TODO Auto-generated method stub
						if (!Util.hasSdcard()) {
							Show.toast(con, R.string.no_sdcard);
							dialog.dismiss();
							return;
						}
						LayoutInflater inflater = LayoutInflater.from(con);
						progressDialog = new Dialog(con);
						progressDialog.setCancelable(false);
						View popView = inflater.inflate(
								R.layout.pop_progress_layout, null);
						progressBar = (ProgressBar) popView
								.findViewById(R.id.progressBar1);
						progressBar.setMax(100);
						progressDialog.getWindow();
						progressDialog
								.requestWindowFeature(Window.FEATURE_NO_TITLE);
						progressDialog.setContentView(popView);
						downFile(App.verinfo.sUpDownLinkAddr);
					}
				});

		// 点取消 ，弹窗消失
		view.findViewById(R.id.exitBtn1).setOnClickListener(
				new OnClickListener() {
					@Override
					public void onClick(View v) {
						// TODO Auto-generated method stub
						if (3 == typeUpgrade)
							finish();
						else
							dialog.dismiss();
					}
				});
		dialog.getWindow();
		dialog.requestWindowFeature(Window.FEATURE_NO_TITLE);
		dialog.setCanceledOnTouchOutside(true);
		dialog.setContentView(view);
		dialog.show();
	}

	public void downFile(final String url) {
		dialog.dismiss();
		progressDialog.show();
		new Thread() {
			public void run() {
				HttpClient client = new DefaultHttpClient();
				HttpGet get = new HttpGet(url);
				HttpResponse response;
				try {
					response = client.execute(get);
					HttpEntity entity = response.getEntity();
					// long length = entity.getContentLength();
					InputStream is = entity.getContent();
					FileOutputStream fileOutputStream = null;
					if (is != null) {
						File file = new File(
								Environment.getExternalStorageDirectory(),
								App.verinfo.sFileName); // Config.UPDATE_SAVENAME
						fileOutputStream = new FileOutputStream(file);
						byte[] buf = new byte[1024];
						int ch = -1;
						int count = 0;
						while ((ch = is.read(buf)) != -1) {
							fileOutputStream.write(buf, 0, ch);
							count += ch;

							index = (int) (count * 100)
									/ (App.verinfo.iFileSize); //
							// fileName
							Log.d("index", String.valueOf(index));
							AcAbout.this.progressDialog = progressDialog;
							Uihandler.sendEmptyMessage(UPDATA);

						}
					}
					fileOutputStream.flush();
					if (fileOutputStream != null) {
						fileOutputStream.close();
					}
					down();
				} catch (ClientProtocolException e) {
					e.printStackTrace();
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
		}.start();
	}

	//
	public void down() {
		Uihandler.post(new Runnable() {
			public void run() {
				progressDialog.cancel();
				update();
			}
		});
	}

	// INSTALL APK
	public void update() {
		Intent intent = new Intent(Intent.ACTION_VIEW);
		intent.setDataAndType(Uri.fromFile(new File(Environment
				.getExternalStorageDirectory(), App.verinfo.sFileName)),
				"application/vnd.android.package-archive"); // Config.UPDATE_SAVENAME
		startActivity(intent);
	}

}